/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "zlang_in.h"

int GitInstall( char *git_url , char *git_branch_name , char *makefile )
{
	char		cmd_buf[ 4096 ] ;
	int		cmd_buf_len ;
	char		*p = NULL ;
	int		nret = 0 ;
	
	p = strrchr( git_url , '/' ) ;
	if( p == NULL )
	{
		printf( "< url[%s] invalid\n" , git_url );
		return -1;
	}
	
	memset( cmd_buf , 0x00 , sizeof(cmd_buf) );
	if( git_branch_name )
	{
		snprintf( cmd_buf , sizeof(cmd_buf)-1 , "git clone --branch %s --single-branch %s" , git_branch_name , git_url );
	}
	else
	{
		snprintf( cmd_buf , sizeof(cmd_buf)-1 , "git clone %s" , git_url );
	}
	printf( "> %s\n" , cmd_buf );
	nret = system( cmd_buf ) ;
	if( nret )
	{
		printf( "< retcode %d\n" , nret );
		return -1;
	}
	
	cmd_buf_len = (int)strlen(p+1) ;
	memmove( cmd_buf , p+1 , cmd_buf_len );
	cmd_buf[cmd_buf_len] = '\0' ;
#define POINT_GIT	".git"
	if( cmd_buf_len > sizeof(POINT_GIT)-1 && MEMCMP( cmd_buf+cmd_buf_len-(sizeof(POINT_GIT)-1) , == , POINT_GIT , sizeof(POINT_GIT)-1 ) )
	{
		cmd_buf_len -= sizeof(POINT_GIT)-1 ;
		cmd_buf[cmd_buf_len] = '\0' ;
	}
	cmd_buf_len += snprintf( cmd_buf+cmd_buf_len , sizeof(cmd_buf)-1-cmd_buf_len , "/src/zobjects" ) ;
	if( GetDirectoryOrFileType(cmd_buf) != FILE_TYPE_DIRECTORY )
	{
		printf( "< [%s] is not a directory\n" , cmd_buf );
		return -1;
	}
	
	printf( "> cd %s\n" , cmd_buf );
#if defined(__linux__)
	nret = chdir( cmd_buf ) ;
#elif defined(_WIN32)
	nret = SetCurrentDirectory( cmd_buf ) ;
#endif
	if( nret )
	{
		printf( "< cd [%s] failed , errno[%d]\n" , cmd_buf , errno );
		return -1;
	}
	
	if( makefile )
	{
		snprintf( cmd_buf , sizeof(cmd_buf)-1 , "make -f %s install" , makefile );
	}
	else
	{
		snprintf( cmd_buf , sizeof(cmd_buf)-1 , "make install" );
	}
	printf( "> %s\n" , cmd_buf );
	nret = system( cmd_buf ) ;
	if( nret )
	{
		printf( "< retcode %d\n" , nret );
		return -1;
	}
	
	strcpy( cmd_buf , "../../../" );
	printf( "> cd %s\n" , cmd_buf );
#if defined(__linux__)
	nret = chdir( cmd_buf ) ;
#elif defined(_WIN32)
	nret = SetCurrentDirectory( cmd_buf ) ;
#endif
	if( nret )
	{
		printf( "< cddir[%s] failed , errno[%d]\n" , cmd_buf , errno );
		return -1;
	}
	
	return 0;
}

